const express = require('express');
const app = express();
const cors = require('cors');
const fs = require('fs');
const path = require('path')
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static('dist'))

const multer = require('multer');

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'data/')
    },
    filename: function (req, file, cb) {
        req.setEncoding('utf-8');
        //解决中文乱码问题
        const original_name = Buffer.from(file.originalname, "latin1").toString("utf8");
        cb(null, original_name)
    }
})

const upload = multer({ storage });

// 指定要读取的目录路径
const directoryPath = path.join(__dirname, 'data');
app.use(cors());
// 定义路由  
app.get('/', (req, res) => {
    res.send('Hello, your API is running!');
});
/*
  http://localhost:3000/users/uploading
*/
app.post('/login', (req, res) => {
    if (req.body.username === 'admin' && req.body.password === 'admin123') {
        res.json({
            success: true,
            data: {
                username: "admin",
                // 一个用户可能有多个角色
                roles: ["admin"],
                accessToken: "eyJhbGciOiJIUzUxMiJ9.admin",
                refreshToken: "eyJhbGciOiJIUzUxMiJ9.adminRefresh",
                expires: "2023/10/30 00:00:00"
            }
        })
    } else {
        res.json({
            success: false,
            message: '用户名密码错误'
        })
    }
})

app.post('/refreshToken', (req, res) => {

    if (req.body.refreshToken) {
        res.json({
            success: true,
            data: {
                accessToken: "eyJhbGciOiJIUzUxMiJ9.newAdmin",
                refreshToken: "eyJhbGciOiJIUzUxMiJ9.newAdminRefresh",
                // `expires`选择这种日期格式是为了方便调试，后端直接设置时间戳或许更方便（每次都应该递增）。如果后端返回的是时间戳格式，前端开发请来到这个目录`src/utils/auth.ts`，把第`38`行的代码换成expires = data.expires即可。
                expires: "2023/10/30 23:59:59"
            }
        })
    } else {
        res.json({
            success: false,
            data: {}
        })
    }


})

app.get('/getAsyncRoutes', (req, res) => {
    const permissionRouter = {
        path: "/permission",
        meta: {
            title: "权限管理",
            icon: "lollipop",
            rank: 10
        },
        children: [
            {
                path: "/permission/page/index",
                name: "PermissionPage",
                meta: {
                    title: "页面权限",
                    roles: ["admin", "common"]
                }
            },
            {
                path: "/permission/button/index",
                name: "PermissionButton",
                meta: {
                    title: "按钮权限",
                    roles: ["admin", "common"],
                    auths: ["btn_add", "btn_edit", "btn_delete"]
                }
            }
        ]
    };


    res.json({
        success: true,
        data: [permissionRouter]
    })
})



app.post('/upload', upload.single('file'), (req, res) => {
    if (req.file) {
        // 文件上传成功
        console.log('File uploaded:', req.file);
    } else {
        // 没有文件上传
        console.log('No file uploaded');
    }

    res.json({
        success: true
    });
})

app.get('/my-report', (req, res) => {
    const id = req.query.id
    const files = fs.readdirSync(directoryPath)
    files.sort()

    const data = JSON.parse(fs.readFileSync(path.join(directoryPath, files[files.length - 1]), 'utf8'))

    // 修改查询条件
    const item = data.find(it => it.id == id)
    if (item) {
        res.json({ success: true, data: item });
    } else {
        res.json({ success: false, message: '没有找到' })
    }
});

app.get('/report', (req, res) => {
    const filename = req.query.filename + '.json'
    let data = fs.readFileSync(path.join(directoryPath, filename), 'utf8')
    data = JSON.parse(data)
    res.json({
        success: true,
        data
    });
});

app.get('/reports', (req, res) => {
    let files = []
    // 调用readdirSync函数同步地获取目录下的所有文件名
    try {
        files = fs.readdirSync(directoryPath);
    } catch (error) {
        console.error("无法读取目录", error);
    }
    res.json({
        data: files,
        success: true
    });
});

// 启动服务器  
app.listen(3000, () => {
    console.log('Server started on port 3000');
});